package com.work.module_base.adapter;


import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;

import java.util.List;

/**
 * Created by Administrator on 2016/9/21 0021.
 * Tablayout适配器
 */
public class CommonFragmentPagerAdapter extends FragmentPagerAdapter {
    private String[] tabTitleArray;
    private List<Fragment> fragmentList;
    private FragmentManager mFragmentManager;

    public CommonFragmentPagerAdapter(FragmentManager fm, List<Fragment> fragmentList, String[] tabTitleArray) {
        super(fm);
        this.mFragmentManager = fm;
        this.fragmentList = fragmentList;
        this.tabTitleArray = tabTitleArray;
    }


    @Override
    public int getCount() {
        return fragmentList.size();
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public long getItemId(int position) {
        super.getItemId(position);
        if (fragmentList != null) {
            if (position < fragmentList.size()) {
                return fragmentList.get(position).hashCode();//important
            }
        }
        return super.getItemId(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (tabTitleArray != null) {
            return tabTitleArray[position % tabTitleArray.length];
        }
        return "";
    }

    /**
     * 从Transaction移除Fragment
     *
     * @param fragment 目标Fragment
     */
    public void removeFragmentInternal(Fragment fragment) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        transaction.remove(fragment);
        transaction.commitNow();
    }

    /**
     * 从Transaction移除所有Fragment
     *
     * @param fragments 目标Fragment
     */
    public void removeFragmentsInternal(List<Fragment> fragments) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        for (int i = 0; i < fragments.size(); i++) {
            transaction.remove(fragments.get(i));
            transaction.commitNow();
        }
    }

}
